<?php
namespace app\mall\logic;

use app\mall_back\model\IntegralConfigModel;
use app\mall_back\model\UserWalletDetailedModel;
use app\mall_back\model\WithdrawApplyModel;
use think\facade\Db;
use think\facade\Log;

class integralLogic{

    /**
     * 积分配置列表
     * @param int $type 类别:1=积分提现;2=兑换金币
     * @return object
     */
    public function integral_list($type):object{
        $IntegralConfigModel = new IntegralConfigModel();
        $list = $IntegralConfigModel->where(['type'=>$type])->order('sort','asc')->select();
        return $list;
    }

    /**
     * 积分提现信息
     * @param array $user 用户信息
     * @param int $id 积分配置id
     * @return array
     */
    public function integral_withdraw_info(array $user,int $id):array{
        if ($user['status']==0){
            return array('code'=>500,'msg'=>'账号已冻结无法提现');
        }
        $IntegralConfigModel = new IntegralConfigModel();
        $integral_config = $IntegralConfigModel->where(['id'=>$id])->find();
        if (!$integral_config){
            return array('code'=>500,'msg'=>'积分提现有误');
        }
        $withdrew_rate = sysdata('withdrew_rate');//提现手续费比例%
        $use_integral = $integral_config['integral'];   //消耗积分
        $commission = bcMath($integral_config['received'],($withdrew_rate/100),'*');//手续费
        $actual_receipt = bcMath($integral_config['received'],$commission,'-'); //实际到账
        $user_integral =  Db::table('one_user_wallet')->where('u_id','=',$user['id'])->value('integral');//查看用户当前积分
        if ($user_integral<$use_integral){
            return array('code'=>500,'msg'=>'积分不足');
        }
        $data = [
            'withdrew_money'=>$integral_config['received'],//提现金额
            'user_integral'=>$user_integral,//用户积分
            'withdrew_rate'=>$withdrew_rate.'%',//手续费
            'use_integral'=>$use_integral,//使用积分
            'commission'=>$commission,//手续费
            'actual_receipt'=>$actual_receipt,//手续费
        ];


        return array('code'=>200,'msg'=>'积分提现','data'=>$data);
    }
    /**
     * 积分提现申请
     * @param int $user 用户信息
     * @param int $id 积分配置id
     * @param int $type 类型：1=提现到微信;2=提现到支付宝
     * @param string $account 账号
     * @param string $real_name 收款人姓名
     * @return array
     */
    public function integral_withdraw_apply(array $user,int $id,int $type,string $account,string $real_name):array{
        if (!in_array($type,[1,2])){
            return array('code'=>500,'msg'=>'提现方式有误');
        }
        if (empty($account)||empty($real_name)){
            return array('code'=>500,'msg'=>'请完善收款信息');
        }
        $IntegralConfigModel = new IntegralConfigModel();
        $integral_config = $IntegralConfigModel->where(['id'=>$id])->find();
        if (!$integral_config){
            return array('code'=>500,'msg'=>'积分提现有误');
        }
        $withdrew_rate = sysdata('withdrew_rate');//提现手续费比例%
        $use_integral = $integral_config['integral'];   //消耗积分
        $commission = bcMath($integral_config['received'],($withdrew_rate/100),'*');//手续费
        $actual_receipt = bcMath($integral_config['received'],$commission,'-'); //实际到账
        $user_integral =  Db::table('one_user_wallet')->where('u_id','=',$user['id'])->value('integral');//查看用户当前积分
        if ($user_integral<$use_integral){
            return array('code'=>500,'msg'=>'积分不足');
        }

        $WithdrawApplyModel = new WithdrawApplyModel();
        $has_reocrd = $WithdrawApplyModel->where(['cate'=>1, 'u_id'=>$user['id'],'status'=>1])->find();
        if ($has_reocrd){
            return array('code'=>500,'msg'=>'请等待上一笔审核后再申请');
        }
        // 启动事务
        Db::startTrans();
        try{
            $now = time();
            //写入提现记录
            $WithdrawApplyModel->save([
                'cate'=>1,
                'sn'=>getSn(),
                'u_id'=>$user['id'],
                'real_name'=>$real_name,
                'account'=>$account,
                'type'=>$type,
                'spend_money'=>$use_integral,
                'money'=>$integral_config['received'],
                'left_money'=>$actual_receipt,
                'poundage'=>$commission,
                'status'=>1,
                'create_time'=>$now,
                'update_time'=>$now,
            ]);
            //扣除用户积分
            Db::table('one_user_wallet')->where('u_id','=',$user['id'])->dec('integral',$integral_config['integral'])->update();//减少余额
            //更新积分变更记录
            walletLogic::wallet_detailed_add($user['id'],$integral_config['integral'],5,2,0,'reduce','积分提现');//增加记录
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::error($e->getMessage());
            return array('code'=>500,'msg'=>'申请失败');
        }


        return array('code'=>200,'msg'=>'申请成功');
    }

    /**
     * 积分提现记录
     * @param int $uid 用户id
     * @param int $page 页数
     * @param int $limit 每页数量
     * @return object
     */
    public function integral_withdraw_list(int $uid,int $page, int $limit):object{
        $where = array(
            array('u_id','=',$uid)
        );

        $WithdrawApplyModel = new WithdrawApplyModel();
        $list = $WithdrawApplyModel->where($where)->order('id','desc')->paginate($limit);

        return $list;
    }

    /**
     * 积分兑换金币
     * @param array $user 用户信息
     * @param int $id 积分配置id
     * @return array
     */
    public function integral_exchange_info(array $user,int $id):array{
        if ($user['status']==0){
            return array('code'=>500,'msg'=>'账号已冻结无法提现');
        }
        $IntegralConfigModel = new IntegralConfigModel();
        $integral_config = $IntegralConfigModel->where(['id'=>$id])->find();
        if (!$integral_config){
            return array('code'=>500,'msg'=>'积分兑换有误');
        }
        $use_integral = $integral_config['integral'];   //消耗积分
        $actual_receipt = $integral_config['received']; //实际到账
        $user_integral =  Db::table('one_user_wallet')->where('u_id','=',$user['id'])->value('integral');//查看用户当前积分
        if ($user_integral<$use_integral){
            return array('code'=>500,'msg'=>'积分不足');
        }
        $data = [
            'exchange_money'=>$integral_config['received'],//兑换金额
            'user_integral'=>$user_integral,//用户积分
            'use_integral'=>$use_integral,//使用积分
            'actual_receipt'=>$actual_receipt,//手续费
        ];


        return array('code'=>200,'msg'=>'积分兑换','data'=>$data);
    }

    /**
     * 积分提现申请
     * @param int $user 用户信息
     * @param int $id 积分配置id
     * @return array
     */
    public function integral_exchange_apply(array $user,int $id):array{

        $IntegralConfigModel = new IntegralConfigModel();
        $integral_config = $IntegralConfigModel->where(['id'=>$id])->find();
        if (!$integral_config){
            return array('code'=>500,'msg'=>'积分兑换有误');
        }
        $use_integral = $integral_config['integral'];   //消耗积分
        $actual_receipt = $integral_config['received']; //实际到账
        $user_integral =  Db::table('one_user_wallet')->where('u_id','=',$user['id'])->value('integral');//查看用户当前积分
        if ($user_integral<$use_integral){
            return array('code'=>500,'msg'=>'积分不足');
        }
        $WithdrawApplyModel = new WithdrawApplyModel();
        // 启动事务
        Db::startTrans();
        try{
            $now = time();
            $WithdrawApplyModel->save([
                'sn'=>getSn(),
                'cate'=>2,
                'u_id'=>$user['id'],
                'spend_money'=>$use_integral,
                'money'=>$actual_receipt,
                'left_money'=>$actual_receipt,
                'poundage'=>0,
                'status'=>1,
                'create_time'=>$now,
                'update_time'=>$now,
            ]);
            $now = time();
            //扣除用户积分
            Db::table('one_user_wallet')->where('u_id','=',$user['id'])->dec('integral',$integral_config['received'])->update();//减少余额
            //更新积分变更记录
            walletLogic::wallet_detailed_add($user['id'],$integral_config['received'],6,2,0,'reduce','积分兑换');//增加记录

            //增加用户余额
            Db::table('one_user_wallet')->where('u_id','=',$user['id'])->inc('money',$integral_config['received'])->update();//增加余额
            //更新余额变更记录
            walletLogic::wallet_detailed_add($user['id'],$integral_config['received'],6,1,0,'add','积分兑换');//增加记录

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::error($e->getMessage());
            return array('code'=>500,'msg'=>'兑换失败');
        }


        return array('code'=>200,'msg'=>'兑换成功');
    }

    /**
     * 积分兑换记录
     * @param int $uid 用户id
     * @param int $page 页数
     * @param int $limit 每页数量
     * @return object
     */
    public function integral_change_list(int $uid,int $page, int $limit):object{
        $where = array(
            array('u_id','=',$uid)
        );

        $WithdrawApplyModel = new WithdrawApplyModel();
        $list = $WithdrawApplyModel->where($where)->order('id','desc')->paginate($limit);

        return $list;
    }

    /**
     * 用户积分变动明细
     * @param int $uid 用户id
     * @param int $page 页数
     * @param int $limit 每页数量
     * @return object
     */
    public function user_integral_change_list(int $uid,int $page, int $limit):object{
        $where = array(
            array('u_id','=',$uid),
            array('genre','=',2)
        );

        $UserWalletDetailedModel = new UserWalletDetailedModel();
        $list = $UserWalletDetailedModel->where($where)->order('id','desc')->paginate($limit);

        return $list;
    }

    /**
     * 用户余额充值记录
     * @param int $uid 用户id
     * @param int $page 页数
     * @param int $limit 每页数量
     * @return object
     */
    public function user_money_recharge_list(int $uid,int $page, int $limit):object{
        $where = array(
            array('u_id','=',$uid),
            array('genre','=',1),
            array('type','in',[1,2,3])
        );

        $UserWalletDetailedModel = new UserWalletDetailedModel();
        $list = $UserWalletDetailedModel->where($where)->order('id','desc')->paginate($limit);

        return $list;
    }
}